package service

import (
	"errors"

	"publish-manage/internal/model"
	"publish-manage/pkg/database"
	"publish-manage/pkg/domain"
	"publish-manage/pkg/util"
)

var AgentPackageService = new(agentPackageService)

type agentPackageService struct{}

func (_ *agentPackageService) Add(instance *model.AgentPackage) (bool, error) {
	if instance.AgentId == "" || instance.PackageId == "" {
		return false, errors.New("代理ID、部署包ID不能为空")
	}

	if c, err := database.DB.Count(&model.AgentPackage{AgentId: instance.AgentId, PackageId: instance.PackageId, Path: instance.Path}); err != nil {
		return false, err
	} else if c > 0 {
		return true, nil
	}

	instance.Id = util.GenerateDatabaseID()
	if _, err := database.DB.Insert(instance); err != nil {
		return false, err
	}

	return false, nil
}

func (_ *agentPackageService) Update(instance *model.AgentPackage) error {
	if instance.Id == "" {
		return errors.New("id不能为空")
	}

	_, err := database.DB.ID(instance.Id).Update(&model.AgentPackage{
		Path:    instance.Path,
		Command: instance.Command,
	})

	return err
}

func (_ *agentPackageService) Delete(id string) error {
	if id == "" {
		return errors.New("id不能为空")
	}

	session := database.DB.NewSession()
	defer session.Close()
	session.Begin()

	if _, err := session.Delete(&model.AgentPackage{Id: id}); err != nil {
		return err
	}
	if _, err := session.Delete(&model.PackageVersion{PackageId: id}); err != nil {
		return err
	}
	return session.Commit()
}

func (_ *agentPackageService) Get(instance *model.AgentPackage) (*model.AgentPackage, error) {
	if instance.Id == "" && (instance.AgentId == "" || instance.PackageId == "") {
		return nil, errors.New("Id 或 代理ID及部署包ID 必须提供 ")
	}

	if exist, err := database.DB.Get(instance); err != nil {
		return nil, err
	} else if !exist {
		return nil, nil
	}
	return instance, nil
}

func (_ *agentPackageService) List(condition *model.AgentPackage, offset, limit int, orderBy string) (pageInfo *domain.Paginate, err error) {
	// 处理不允许查询的字段
	condition.Command = ""

	// 处理sql
	session := database.DB.NewSession()
	if limit > -1 && offset > -1 {
		session.Limit(limit, offset)
	}

	if orderBy != "" {
		session.OrderBy(orderBy)
	}
	session.Desc("create_time")

	// 模糊查找
	if condition.Path != "" {
		session.Where("path like ?", condition.Path+"%")
		condition.Path = ""
	}

	var list []*model.AgentPackage
	total, err := session.FindAndCount(&list, condition)
	if err != nil {
		return nil, err
	}

	return &domain.Paginate{
		Total:  int(total),
		Offset: offset,
		Limit:  limit,
		Items:  list,
	}, nil
}
